package com.mrd.shiptask_shipowner;

import java.util.HashMap;
import java.util.Map;

import com.mrd.shiptask_shipowner.activity.ElectronManifestActivity;
import com.mrd.shiptask_shipowner.activity.MainActivity;
import com.mrd.shiptask_shipowner.activity.NewsActivity;
import com.mrd.shiptask_shipowner.constants.HttpConstant;
import com.mrd.shiptask_shipowner.hwpush.PustDemoActivity;
import com.mrd.shiptask_shipowner.serviecs.BizNetworkService;
import com.mrd.shiptask_shipowner.shiareutil.SharePreferenceUtil;
import com.mrd.shiptask_shipowner.unit_tools.DatasTools;
import com.mrd.shiptask_shipowner.unit_tools.FunctionOfActivity;
import com.mrd.shiptask_shipowner.unit_tools.HttpUrlConstant;
import com.mrd.shiptask_shipowner.unit_tools.SysApplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {
	private LoginActivity THIS = LoginActivity.this;
	private EditText accountEt, pwdEt;
	private CheckBox remeberPassword;
	private Button loginBt;
	private ProgressDialog progressDialog;
	private SharePreferenceUtil spu;
	private TextView versionCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		// 设置全屏\ 设置横屏
		progressDialog = new ProgressDialog(THIS);
		spu = new SharePreferenceUtil(THIS);
		initViewAction();
		// startActivity(new Intent(THIS, ElectronManifestActivity.class));
		// 启动需要的service服务
		initServiceAction();
		// 版本检查
		checkVersionAndUpdate();
		SysApplication.getInstance().addActivity(this);
	}

	private void checkVersionAndUpdate() {
		// TODO Auto-generated method stub
		// 请求服务器apk信息
		new Thread(new BizNetworkService(THIS, handlers,
				HttpUrlConstant.CHECK_VERSION_AND_UPDATE, null)).start();
	}

	private void initServiceAction() {
		// TODO Auto-generated method stub
		/**
		 * 启动后台service
		 */
		Intent service = new Intent("com.receivers.selfrunningservice");
		service.setPackage(getPackageName());
		startService(service);
	}

	private void initViewAction() {
		// TODO Auto-generated method stub
		accountEt = (EditText) findViewById(R.id.AccountEt);
		pwdEt = (EditText) findViewById(R.id.pwdEt);
		pwdEt.setInputType(InputType.TYPE_CLASS_TEXT
				| InputType.TYPE_TEXT_VARIATION_PASSWORD);
		remeberPassword = (CheckBox) findViewById(R.id.remeberPassword);
		loginBt = (Button) findViewById(R.id.loginB);
		loginBt.setOnClickListener(ocl);
		// 初始化输入的账号密码
		accountEt.setText(spu.getLoginAccount());
		pwdEt.setText(spu.getLoginPasswd());
		// 如缓存账号有记录，则表示上次登录为勾选，所以勾选保留
		if (spu.getLoginPasswd().length() > 0) {
			remeberPassword.setChecked(true);
		}
		versionCode = (TextView) findViewById(R.id.versionCode);
		// 版本信息
		String shipbiz = HttpUrlConstant.SHIPBIZ_BASE_URL.replace(
				"http://www.chuanhuoe.com:", "");
		String smas = (HttpUrlConstant.BASE_URL.replace(
				"http://www.56cyt.com:", "")).replace("/smas_pf", "");
		String versionHead = "测试版本";
		if ("8088".equals(shipbiz) && "8381".equals(smas)) {
			versionHead = "正式版本";
		}
		String versionStr = versionHead + "：船货交易_v"
				+ DatasTools.getVersion(THIS) + "_MRD"
				+ HttpUrlConstant.releaseDate + "\n*版权所有 翻版必究*";
		versionCode.setText(versionStr);
	}

	private final OnClickListener ocl = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			switch (arg0.getId()) {
			case R.id.loginB:
				// 提交是检查账号密码是否输入正确
				if (checkInfoEditStatus()) {
					// 提交前检查网络是否可用
					if (FunctionOfActivity.isNetworkAvailable(THIS)) {

						progressDialog.setMessage("正在登录，请稍后。。。");
						progressDialog.show();
						final String userName = accountEt.getText().toString();
						final String password = pwdEt.getText().toString();
						Map<String, Object> params = new HashMap<String, Object>();
						params.put("account", userName);
						params.put("password", password);
						// 登录识别app
						params.put("appType", "CHE");
						new Thread(new BizNetworkService(THIS, mHandler,
								HttpUrlConstant.LOGIN, params)).start();

					} else {
						FunctionOfActivity.makeToaskShow(THIS, "当前网络不可用");
					}

				}
				break;

			default:
				break;
			}
		}

		private boolean checkInfoEditStatus() {
			// TODO Auto-generated method stub
			// 输入的账号内容
			String accountInfo = accountEt.getText().toString();
			// 密码的内容
			String passwordInfo = pwdEt.getText().toString();
			if (accountInfo.length() <= 0) {
				FunctionOfActivity.makeToaskShow(THIS, "账号不能为空");
				return false;
			} else if (passwordInfo.length() <= 0) {
				FunctionOfActivity.makeToaskShow(THIS, "密码不能为空");
				return false;
			}
			return true;
		}

	};
	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle data = msg.getData();
			if (!data.isEmpty()) {
				THIS.progressDialog.dismiss();
				switch (msg.what) {
				case HttpUrlConstant.LOGIN:
					try {
						if (data.getBoolean("result")) {
							Intent intent = new Intent(THIS, MainActivity.class);
							// put入检查app版本的打开标记
							startActivity(intent);
							// 初始化记录不同账号的数据
							DatasTools.initDatasAboutDifferenceAccount(THIS);

						}
						FunctionOfActivity.makeToaskShow(THIS,
								data.getString("msg"));
						if (remeberPassword.isChecked()) {
							// 勾选记住密码时保存账号密码
							spu.setLoginAccount(accountEt.getText().toString());
							spu.setLoginPasswd(pwdEt.getText().toString());
						} else {
							spu.setLoginAccount(accountEt.getText().toString());
							spu.setLoginPasswd("");
						}
						break;
					} catch (Exception e) {
						// TODO: handle exception
						THIS.progressDialog.dismiss();
					}
				}
			} else {
				THIS.progressDialog.dismiss();
				FunctionOfActivity.makeToaskShow(THIS, "登录异常，请重试！");
			}
		}
	};

	/**
	 * 點擊EditText以外的區域后鍵盤隱藏
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {

			// 获取当前获得当前焦点所在View
			View view = getCurrentFocus();
			if (FunctionOfActivity.isClickEt(view, event)) {

				// 如果不是edittext，则隐藏键盘

				InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				if (inputMethodManager != null) {
					// 隐藏键盘
					inputMethodManager.hideSoftInputFromWindow(
							view.getWindowToken(), 0);
				}
			}
			return super.dispatchTouchEvent(event);
		}
		/**
		 * 看源码可知superDispatchTouchEvent 是个抽象方法，用于自定义的Window
		 * 此处目的是为了继续将事件由dispatchTouchEvent(MotionEvent
		 * event)传递到onTouchEvent(MotionEvent event) 必不可少，否则所有组件都不能触发
		 * onTouchEvent(MotionEvent event)
		 */
		if (getWindow().superDispatchTouchEvent(event)) {
			return true;
		}
		return onTouchEvent(event);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 这里重写返回键
			Intent startMain = new Intent(Intent.ACTION_MAIN);
			startMain.addCategory(Intent.CATEGORY_HOME);
			startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(startMain);
			System.exit(0);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		SysApplication.getInstance().exit(true);
		Intent i = new Intent(Intent.ACTION_MAIN);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.addCategory(Intent.CATEGORY_HOME);
		startActivity(i);
	}

	/**
	 * 调用升级action UpdataAppAction
	 */
	@SuppressLint("HandlerLeak")
	public Handler handlers = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			try {
				Bundle data = msg.getData();
				progressDialog.dismiss();
				if (!data.isEmpty()) {
					switch (msg.what) {
					case HttpUrlConstant.CHECK_VERSION_AND_UPDATE:
						if (HttpConstant.HAS_NEW_VERSION.equals(data
								.getString(HttpConstant.OPA_TAG))) {
							// 调用下载部分
							DatasTools.downVersionAction(THIS,
									data.getString("result"));
						} else if (HttpConstant.HAS_NO_VERSION.equals(data
								.getString(HttpConstant.OPA_TAG))) {
						} else {

						}
						break;
					default:
						break;
					}
				} else {
				}
			} catch (Exception e) {
			}
		}

	};
}
